package com.googlecode.groovy_toy_orm

/**
 * @author: DavydovMD
 * Date: 25.04.13
 * Time: 15:51
 */
public class MapperBinding {
    SingleDbTableMapper mapper = null
    JoinType joinType = JoinType.LEFT_OUTER
    List<Condition> conditionsList = []
    String locator = null

    MapperBinding(SingleDbTableMapper mapper) {
        this.mapper = mapper
    }

    MapperBinding(List<SingleDbTableMapper> mappers, String locator) {
        this.mapper = findMapper(mappers, locator)
    }

    MapperBinding(String locator) {
        this.locator = locator
    }


    public void locateMapper(List<SingleDbTableMapper> mappers) {
        if (locator)
            this.mapper = findMapper(mappers, locator)
    }

    MapperBinding withJoinType(JoinType joinType) {
        this.joinType = joinType
        this
    }

    MapperBinding withConditions(List conditions) {
        this.conditionsList.addAll(conditions)
        this
    }

    /**
     * Returns first mapper with prefix matching locator, e.g., locator 'User' for mappers [User.table1, User.table2, Deals.table1] will return User.table1
     * @param mappers
     * @param locator
     * @return
     */
    static private SingleDbTableMapper findMapper(List<SingleDbTableMapper> mappers, String locator) {
        mappers.find {
            it.getPrefix().contains(locator)
        }
    }

}
